package main

import (
	"os"
	"time"

	"gitee.com/congqian/dense-spider/core/common/com_interfaces"
	"gitee.com/congqian/dense-spider/core/common/mlog"
	"gitee.com/congqian/dense-spider/core/common/page_items"
	"github.com/go-xorm/xorm"
	_ "github.com/mattn/go-sqlite3"

	"errors"
)

const (
	dbtype = "sqlite"
)

type Project struct {
	Id           int64
	Content      string    `xorm:"text"`
	Title        string    `xorm:"varchar(128)"`
	Name         string    `xorm:"varchar(128)"`
	Code         string    `xorm:"varchar(64)"`
	Tag          string    `xorm:"varchar(64)"`
	PublishAt    string    `xorm:"created index"`
	Target       string    `xorm:"varchar(64)"`
	Province     string    `xorm:"varchar(32)"`
	City         string    `xorm:"varchar(32)"`
	County       string    `xorm:"varchar(32)"`
	Url          string    `xorm:"varchar(256)"`
	Created      time.Time `xorm:"created index"`
	DocPublished time.Time `xorm:"index"`
}

var (
	engine *xorm.Engine
)

func init() {
	SetEngine()
	CreatTables()
}

func ConDb() (*xorm.Engine, error) {
	switch {
	case dbtype == "sqlite":
		return xorm.NewEngine("sqlite3", "./data/sqlite.db")

	case dbtype == "mysql":
		return xorm.NewEngine("mysql", "root:123456@tcp(localhost:3306)/go_spider?charset=utf8")

	case dbtype == "pgsql":
		// "user=postgres password=^%*&^%#@* dbname=pgsql sslmode=disable maxcons=10 persist=true"
		//return xorm.NewEngine("postgres", "host=110.76.39.205 user=postgres password=^%*&^%#@* dbname=pgsql sslmode=disable")
		return xorm.NewEngine("postgres", "user=postgres password=^%*&^%#@* dbname=sdc sslmode=disable")
		//return xorm.NewEngine("postgres", "host=127.0.0.1 port=6432 user=postgres password=^%*&^%#@* dbname=sdc sslmode=disable")
	}
	return nil, errors.New("尚未设定数据库连接")
}

func SetEngine() (*xorm.Engine, error) {

	var err error
	if engine == nil {
		engine, err = ConDb()
	}

	//Engine.Mapper = xorm.SameMapper{}

	engine.SetMaxOpenConns(100)
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 10000)
	engine.SetDefaultCacher(cacher)

	f, err := os.Create("./logs/sql.log")
	if err != nil {
		mlog.LogInst().LogError(err.Error())
	}
	engine.SetLogger(xorm.NewSimpleLogger(f))

	return engine, err
}

func CreatTables() error {

	return engine.Sync2(new(Project))
}

type PipelineDb struct {
}

func NewPipelineDb() *PipelineDb {
	return &PipelineDb{}
}
func (this *PipelineDb) Process(items *page_items.PageItems, t com_interfaces.Task) {
	doc := new(Project)
	content, ok := items.GetItem("Content")
	if !ok {
		content = ""
	}

	title, ok := items.GetItem("Title")
	if !ok {
		title = ""
	}
	if content == "" && title == "" {
		return
	}
	name, ok := items.GetItem("Name")
	if !ok {
		name = ""
	}
	code, ok := items.GetItem("Code")
	if !ok {
		code = ""
	}
	tag, ok := items.GetItem("Tag")
	if !ok {
		tag = ""
	}
	publishAt, ok := items.GetItem("PublishAt")
	if !ok {
		publishAt = ""
	}
	target, ok := items.GetItem("Target")
	if !ok {
		target = ""
	}
	county, ok := items.GetItem("County")
	if !ok {
		county = ""
	}
	city := "成都"
	province := "四川"
	var docPublishedTime time.Time = time.Now()
	var err = errors.New("时间格式错误")
	docPublished, ok := items.GetItem("DocPublished")
	if ok {
		docPublishedTime, err = time.Parse("2006-01-02 15:04:05", docPublished)
		if err != nil {
			mlog.LogInst().LogError(err.Error())

		}
	}

	doc = &Project{
		Name:         name,
		Code:         code,
		Tag:          tag,
		PublishAt:    publishAt,
		Target:       target,
		City:         city,
		Province:     province,
		County:       county,
		Title:        title,
		Content:      content,
		Url:          items.GetRequest().GetUrl(),
		DocPublished: docPublishedTime,
		Created:      time.Now()}
	_, err = engine.Insert(doc)
	if err != nil {
		mlog.LogInst().LogError(err.Error())
	}
}
